package org.jeecgframework.web.controller;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsSlaServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.pojo.base.CbsSlaEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 合同服务条款
 * @date 2017-12-22 14:43:04
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsSlaController")
public class CbsSlaController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger ( CbsSlaController.class );

    @Autowired
    private CbsSlaServiceI cbsSlaService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyCommonService zyCommonService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 合同服务条款列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsSla")
    public ModelAndView cbsSla(HttpServletRequest request) {
        return new ModelAndView ( "com/zybk/cbssla/cbsSlaList" );
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsSlaEntity cbsSla, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery ( CbsSlaEntity.class, dataGrid );
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql ( cq, cbsSla, request.getParameterMap () );
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException ( e.getMessage () );
        }
        cq.add ();
        this.cbsSlaService.getDataGridReturn ( cq, true );
        TagUtil.datagrid ( response, dataGrid );
    }

    /**
     * 合同服务条款新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsSlaEntity cbsSla, HttpServletRequest req) {
        return new ModelAndView ( "com/zybk/cbssla/cbsSla-add" );
    }


    /**
     * 添加合同服务条款
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsSlaEntity cbsSla, HttpServletRequest request) {
        AjaxJson j = new AjaxJson ();
        message = "合同服务条款添加成功";
        try {
            Map<String, Object> slaMap = systemService.findOneForJdbc ( "SELECT t.id FROM CBS_SLA t where t.service_name = '"+cbsSla.getServiceName()+"'" );
            if(slaMap != null){
                message = "服务条款名称不能重复";
            }else{
                cbsSla.setIsUse(1);//是否在使用中：是
                cbsSlaService.save ( cbsSla );
                systemService.addLog ( message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO );
            }
        } catch (Exception e) {
            e.printStackTrace ();
            message = "合同服务条款添加失败";
            throw new BusinessException ( e.getMessage () );
        }
        j.setMsg ( message );
        return j;
    }

    /**
     * 合同服务条款编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsSlaEntity cbsSla, HttpServletRequest req) {
        if (StringUtil.isNotEmpty ( cbsSla.getId () )) {
            cbsSla = cbsSlaService.getEntity ( CbsSlaEntity.class, cbsSla.getId () );
            req.setAttribute ( "cbsSlaPage", cbsSla );
        }
        return new ModelAndView ( "com/zybk/cbssla/cbsSla-update" );
    }

    /**
     * 更新合同服务条款
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsSlaEntity cbsSla, HttpServletRequest request) {
        AjaxJson j = new AjaxJson ();
        message = "合同服务条款更新成功";
        CbsSlaEntity t = cbsSlaService.get ( CbsSlaEntity.class, cbsSla.getId () );
        try {
            MyBeanUtils.copyBeanNotNull2Bean ( cbsSla, t );
            cbsSlaService.saveOrUpdate ( t );
            systemService.addLog ( message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO );
        } catch (Exception e) {
            e.printStackTrace ();
            message = "合同服务条款更新失败";
            throw new BusinessException ( e.getMessage () );
        }
        j.setMsg ( message );
        return j;
    }

    /**
     * 校验表单信息
     * @return
     */
    @RequestMapping(params = "checkInfo")
    @ResponseBody
    public ValidForm checkInfo(@RequestParam(value="param",defaultValue="")String param,
                    @RequestParam(value="id",defaultValue="")String id) {
        ValidForm vf = new ValidForm();
        StringBuffer sb = new StringBuffer();
        sb.append("select count(1) as total from cbs_sla t where t.service_name = '"+param+"'");
        if(StringUtil.isNotEmpty(id)){
            sb.append(" and t.id != '"+id+"'");
        }
        int total = zyCommonService.getCountBySql(sb.toString());
        if(total > 0){
            vf.setStatus(ValidForm.N);
            vf.setInfo("当前服务条款名称已存在");
        }
        return vf;
    }


    /**
     * 删除合同服务条款
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsSlaEntity cbsSla, HttpServletRequest request) {
        AjaxJson j = new AjaxJson ();
        cbsSla = systemService.getEntity ( CbsSlaEntity.class, cbsSla.getId () );
        message = "合同服务条款删除成功";
        try {
            cbsSlaService.delete ( cbsSla );
            systemService.addLog ( message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO );
        } catch (Exception e) {
            e.printStackTrace ();
            message = "合同服务条款删除失败";
            throw new BusinessException ( e.getMessage () );
        }
        j.setMsg ( message );
        return j;
    }

    /**
     * 批量删除合同服务条款
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson ();
        message = "合同服务条款删除成功";
        try {
            for (String id : ids.split ( "," )) {
                CbsSlaEntity cbsSla = systemService.getEntity ( CbsSlaEntity.class,
                        id
                );
                cbsSlaService.delete ( cbsSla );
                systemService.addLog ( message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO );
            }
        } catch (Exception e) {
            e.printStackTrace ();
            message = "合同服务条款删除失败";
            throw new BusinessException ( e.getMessage () );
        }
        j.setMsg ( message );
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView ( "com/zybk/cbssla/cbsSlaUpload" );
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsSlaEntity cbsSla, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery ( CbsSlaEntity.class, dataGrid );
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql ( cq, cbsSla, request.getParameterMap () );
        List<CbsSlaEntity> cbsSlas = this.cbsSlaService.getListByCriteriaQuery ( cq, false );
        modelMap.put ( NormalExcelConstants.FILE_NAME, "合同服务条款" );
        modelMap.put ( NormalExcelConstants.CLASS, CbsSlaEntity.class );
        modelMap.put ( NormalExcelConstants.PARAMS, new ExportParams ( "合同服务条款列表", "导出人:" + ResourceUtil.getSessionUserName ().getRealName (),
                "导出信息" ) );
        modelMap.put ( NormalExcelConstants.DATA_LIST, cbsSlas );
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsSlaEntity cbsSla, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put ( TemplateExcelConstants.FILE_NAME, "合同服务条款" );
        modelMap.put ( TemplateExcelConstants.PARAMS, new TemplateExportParams ( "Excel模板地址" ) );
        modelMap.put ( TemplateExcelConstants.MAP_DATA, null );
        modelMap.put ( TemplateExcelConstants.CLASS, CbsSlaEntity.class );
        modelMap.put ( TemplateExcelConstants.LIST_DATA, null );
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson ();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap ();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet ()) {
            MultipartFile file = entity.getValue ();// 获取上传文件对象
            ImportParams params = new ImportParams ();
            params.setTitleRows ( 2 );
            params.setHeadRows ( 1 );
            params.setNeedSave ( true );
            try {
                List<CbsSlaEntity> listCbsSlaEntitys = ExcelImportUtil.importExcelByIs ( file.getInputStream (), CbsSlaEntity.class, params );
                for (CbsSlaEntity cbsSla : listCbsSlaEntitys) {
                    cbsSlaService.save ( cbsSla );
                }
                j.setMsg ( "文件导入成功！" );
            } catch (Exception e) {
                j.setMsg ( "文件导入失败！" );
                logger.error ( ExceptionUtil.getExceptionMessage ( e ) );
            } finally {
                try {
                    file.getInputStream ().close ();
                } catch (IOException e) {
                    e.printStackTrace ();
                }
            }
        }
        return j;
    }
}
